﻿// Written by Dale J Williams.
// Licensed under MPL 1.1 unless otherwise specified. 
// http://www.mozilla.org/MPL/MPL-1.1.html

package engineDJW.tween {
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	
	/**
	 * TweenManager: Manages Tween animation.
	 * @author Dale J Williams
	 */
	public class TweenManager {
		
		public var frames		:int;
		public var difference	:int;
		public var time			:int;
		public var fps			:Number;
		
		private var _sprite		:Sprite 	= new Sprite();
		private var _tweens		:Dictionary	= new Dictionary(false);
		
		public function TweenManager() {
			init();
		}
		
		private function init():void {
			_sprite.addEventListener(Event.ENTER_FRAME, update);
		}
		
		private function update(e:Event=null):void {
			frames++; 													
			difference = getTimer() - time; 						
			time += difference;						
			fps = frames / time * 1000;
			for each(var tween:Tween in _tweens)
				tween.update(time); 		
		}
		
		public function to($target:Object, $duration:Number, $properties:Object):Tween { 
			if (!$target) throw new Error("Can not Tween a null target.");
			if (_tweens[$target]) kill($target);
			var tween:Tween = _tweens[$target] = new Tween();	
			tween.manager = this;
			tween.init($target, $duration, $properties);
			return tween;
		}
		
		public function kill(target:Object):void {
			if (_tweens[target])
				delete _tweens[target];
		}
		
		public function isTweening(target:Object):Boolean {
			return _tweens[target] != null;
		}
		
		public function getTween(target:Object):Tween {
			return _tweens[target] || null;
		}
		
	}	
}